<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="权限名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-select v-model="listQuery.type" placeholder="权限类型" clearable style="width: 150px">
        <el-option label="菜单权限" value="menu" />
        <el-option label="按钮权限" value="button" />
        <el-option label="API权限" value="api" />
      </el-select>
      <el-button v-has-perm="'view:permission'" class="filter-item" type="primary" @click="handleFilter">
        查询
      </el-button>
      <el-button v-has-perm="'add:permission'" v-test-account class="filter-item" type="success" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column prop="id" label="ID" align="center" width="80" />
      <el-table-column prop="name" label="权限名称" min-width="150" />
      <el-table-column prop="code" label="权限标识" min-width="150" />
      <el-table-column prop="type" label="权限类型" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.type === 'menu'" type="success">菜单权限</el-tag>
          <el-tag v-else-if="row.type === 'button'" type="warning">按钮权限</el-tag>
          <el-tag v-else-if="row.type === 'api'" type="info">API权限</el-tag>
          <el-tag v-else type="danger">未知类型</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="权限描述" min-width="200" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" align="center" width="180">
        <template #default="{ row }">
          <el-button v-has-perm="'edit:permission'" v-test-account size="small" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-has-perm="'delete:permission'" v-test-account size="small" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      :total="total"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="listQuery.limit"
      v-model:current-page="listQuery.page"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 权限编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form
        ref="dataForm"
        :model="tempPermission"
        :rules="rules"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="tempPermission.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="tempPermission.code" placeholder="如：view:user, add:user" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="tempPermission.type" placeholder="请选择权限类型" style="width: 100%">
            <el-option label="菜单权限" value="menu" />
            <el-option label="按钮权限" value="button" />
            <el-option label="API权限" value="api" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input 
            v-model="tempPermission.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入权限描述" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button v-test-account type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPermissions, createPermission, updatePermission, deletePermission } from '@/api/permission'

const list = ref([])
const total = ref(0)
const listLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dataForm = ref(null)

const listQuery = reactive({
  page: 1,
  limit: 10,
  name: '',
  type: ''
})

const tempPermission = reactive({
  id: undefined,
  name: '',
  code: '',
  type: 'button',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
  type: [{ required: true, message: '请选择权限类型', trigger: 'change' }]
}

// 获取权限列表
const getList = async () => {
  listLoading.value = true
  try {
    const response = await getPermissions()
    list.value = response.data || []
    total.value = list.value.length
  } catch (error) {
    console.error('获取权限列表失败', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    listLoading.value = false
  }
}

// 筛选
const handleFilter = () => {
  listQuery.page = 1
  getList()
}

// 每页数量变化
const handleSizeChange = (val) => {
  listQuery.limit = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  listQuery.page = val
  getList()
}

// 创建权限
const handleCreate = () => {
  dialogTitle.value = '创建权限'
  dialogVisible.value = true
  
  // 重置表单
  nextTick(() => {
    if (dataForm.value) {
      dataForm.value.resetFields()
    }
    
    Object.assign(tempPermission, {
      id: undefined,
      name: '',
      code: '',
      type: 'button',
      description: ''
    })
  })
}

// 更新权限
const handleUpdate = (row) => {
  dialogTitle.value = '编辑权限'
  dialogVisible.value = true
  
  // 重置表单并填充数据
  nextTick(() => {
    if (dataForm.value) {
      dataForm.value.resetFields()
    }
    
    Object.assign(tempPermission, row)
  })
}

// 删除权限
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该权限吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deletePermission(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除权限失败', error)
      ElMessage.error('删除权限失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!dataForm.value) return
  
  // 表单验证
  try {
    await dataForm.value.validate()
    
    // 是新增还是编辑
    if (tempPermission.id === undefined) {
      // 新增
      await createPermission(tempPermission)
      ElMessage.success('创建成功')
    } else {
      // 编辑
      await updatePermission(tempPermission.id, tempPermission)
      ElMessage.success('更新成功')
    }
    
    // 关闭对话框并刷新列表
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
}

.dialog-footer {
  text-align: right;
}
</style> 